package com.bbf.springmvcdemo.util;

import com.bbf.springmvcdemo.feature.ServiceResult;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常拦截器，通过判断是否有@ResponseBody注解，返回不同的错误。
 * @author BBF
 */
public final class MyExceptionResolver extends SimpleMappingExceptionResolver {
  @Override
  protected ModelAndView doResolveException(HttpServletRequest request,
                                            HttpServletResponse response,
                                            Object handler,
                                            Exception ex) {
    HandlerMethod method = (HandlerMethod) handler;
    ResponseBody body = method.getMethodAnnotation(ResponseBody.class);
    // 判断有没有@ResponseBody的注解，没有则调用父方法
    if (null == body) {
      return super.doResolveException(request, response, handler, ex);
    }
    ServiceResult<String> result = new ServiceResult<>();
    response.setStatus(BaseUtil.HTTP500);
    result.setError(ex.getMessage());
    String json = JsonUtil.toJson(result);
    // 设置ContentType
    response.setContentType(BaseUtil.JSON);
    response.setCharacterEncoding(BaseUtil.UTF8);
    ModelAndView modelAndView = new ModelAndView();
    response.setHeader("Cache-Control", "no-cache, must-revalidate");
    modelAndView.addObject("json", json);
    modelAndView.setViewName("common/json");
    return modelAndView;
  }
}
